#!/bin/bash

# 函数：设置Ubuntu的APT源
setUbuntuSources() {
  local version=$1
  local codeName=$2
  local base_url="https://mirrors.aliyun.com/ubuntu/"
  local sources_file="/etc/apt/sources.list"

  # Ubuntu 24及以后版本使用新的配置文件路径
  if [[ $version -ge 24 ]]; then
    sudo bash -c "cat <<EOF >/etc/apt/sources.list.d/ubuntu.sources
Types: deb
URIs: https://mirrors.aliyun.com/ubuntu/
Suites: noble noble-updates noble-backports
Components: main universe restricted multiverse
Signed-By: /usr/share/keyrings/ubuntu-archive-keyring.gpg

# Ubuntu security updates. Aside from URIs and Suites,
# this should mirror your choices in the previous section.
Types: deb
URIs: https://mirrors.aliyun.com/ubuntu/
Suites: noble-security
Components: main universe restricted multiverse
Signed-By: /usr/share/keyrings/ubuntu-archive-keyring.gpg
EOF"
  else
    # 重置sources.list或ubuntu.sources
    sudo echo "deb $base_url $codeName main restricted universe multiverse" >$sources_file
    sudo echo "deb-src $base_url $codeName main restricted universe multiverse" >>$sources_file

    # 添加其他源
    for repo in security updates backports proposed; do
      sudo echo "deb $base_url ${codeName}-$repo main restricted universe multiverse" >>$sources_file
      sudo echo "deb-src $base_url ${codeName}-$repo main restricted universe multiverse" >>$sources_file
    done
  fi
}

# 主函数：根据系统版本更改源
changeSource() {
  local uVersion=$(lsb_release -rs | cut -d. -f1)
  echo "自动修改apt源为阿里源，支持Ubuntu 16、18、20、22、24,当前系统版本为: $uVersion"
  declare -A versions=(
    [16]="xenial"
    [18]="bionic"
    [20]="focal"
    [22]="jammy"
    [24]="noble"
  )

  if [[ ${versions[$uVersion]} ]]; then
    setUbuntuSources $uVersion ${versions[$uVersion]}
  else
    echo "不支持的Ubuntu版本: $uVersion"
    return 1
  fi

  sudo apt-get update
}
